package net.diaowen.dwsurvey.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import net.diaowen.dwsurvey.entity.LotteryActivity;
import net.diaowen.dwsurvey.entity.LotteryPrize;
import net.diaowen.dwsurvey.entity.PrizeType;
import net.diaowen.dwsurvey.service.LotteryActivityManager;
import net.diaowen.dwsurvey.service.LotteryPrizeManager;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;

@Controller
@RequestMapping("/sy/lottery/prize")
public class LotteryPrizeController{
	
	@Autowired
	private LotteryPrizeManager lotteryPrizeManager;
	
	@Autowired
	private LotteryActivityManager lotteryActivityManager;
	
	@Autowired
	private SurveyDirectoryManager surveyDirectoryManager;
// 奖项设置
	@RequestMapping("/init.do")
	public ModelAndView list(String id) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		LotteryPrize lp = lotteryPrizeManager.getByActivityId(id);
        if (lp == null) {
        	modelAndView.addObject("id", id);
        	List<PrizeType> prizeTypeList = lotteryPrizeManager.getPrizeTypeList();
        	modelAndView.addObject("prizeTypeList", prizeTypeList);
        	modelAndView.setViewName("/diaowen-lottery/prize_e");
        } else {
        	modelAndView.addObject("lp", lp);
        	modelAndView.setViewName("/diaowen-lottery/prize_d");
        }
		return modelAndView;
	}
	
	
	@RequestMapping("/save.do")
	public ModelAndView save(LotteryPrize entity) throws Exception {
		lotteryPrizeManager.savePrizeSetting(entity);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("redirect:/sy/lottery/list.do");
		return modelAndView;
	}
	// 重置奖项
	@RequestMapping("/reset.do")
	public ModelAndView reset(String id) throws Exception {
		//TODO后期这里再加一个check
		lotteryPrizeManager.resetPrizeSetting(id);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("id", id);
		List<PrizeType> prizeTypeList = lotteryPrizeManager.getPrizeTypeList();
		modelAndView.addObject("prizeTypeList", prizeTypeList);
		modelAndView.setViewName("/diaowen-lottery/prize_e");
		return modelAndView;
	}

	
    @RequestMapping("/getSurveyAnswerCount.do")
    @ResponseBody
    public String checkActivityStatus(HttpServletRequest request,HttpServletResponse response,String id) throws IOException{
    	//获得问卷应该参与的人数，从v_student_survey查找
    	LotteryActivity lotteryActivity = lotteryActivityManager.get(id);
    	String surveyId = lotteryActivity.getSurveyId();
    	Long count = surveyDirectoryManager.getSurveyPartyUser(surveyId);
		response.getWriter().write(String.valueOf(count));
		return null;
    }
}
